package org.winplus.sh;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


/**
 * 录音 searchWithPath(String path) 根据指定查询条件通过MediaStore 来查询录音文件信息并用数组形式保存传值
 * 
 * @author huwei
 * @version 2012-9-26
 */
public class RecordtimeActivity extends Activity {
	protected static final String assetManager = null;
	// 指定查询条件
	String selection = MediaStore.Audio.Media.DATA + " like ?";

	// 设定查询目录
	String path = "/mnt/sdcard/Recording";
	private int second = 0;// 音频的时长 秒
	private int minute = 0;// 音频的分钟数
	private int remain = 0;// 音频的秒数
	private String year, mounth, day, hour, minuets;// 分别代表年月日时分
	int counter;
	String[] data;// 保存每一个音频录取日期
	String[] time;// 保存每个音频录取时间
	String[] time_length;// 保存每个音频时间长度
	String[] root;// 每個文件的路徑
	TextView textView;
	ListView listView;
	Button butl1;//返回按钮
	Button btn_new;//刷新列表按钮
	RecordAdapter adapter;
	int i;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listview);

		// 根据ID找到相应的控件
		listView = (ListView) findViewById(R.id.list);
		butl1 = (Button) findViewById(R.id.butl1);
		btn_new=(Button)findViewById(R.id.record_new);

		// 返回按钮的监听事件
		butl1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(RecordtimeActivity.this,
						SoundHandActivity.class);// 跳转回录音界面
				startActivity(intent);
				RecordtimeActivity.this.finish();
			}
		});
		btn_new.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				scanSdCard();
				// TODO Auto-generated method stub
				final Handler handler = new Handler() {
				public void handleMessage(Message msg) {
					super.handleMessage(msg);
					Bundle bundle = msg.getData();
					int n = bundle.getInt("age");
					if (n == 2) {
						Intent intent = new Intent(
								RecordtimeActivity.this,
								RecordtimeActivity.class);// 加载入公司介绍
						startActivity(intent);
						intent = null;
						finish();// 完成加载页
					}
				}

			};

			new Timer().schedule(new TimerTask() {
				public void run() {
					i = i + 1;
					Message msg = handler.obtainMessage();
					msg.arg1 = i;
					Bundle bundle = new Bundle();
					bundle.putInt("age", msg.arg1);
					msg.setData(bundle);
					msg.sendToTarget();
					
				}
			}, 5000, 1000);
			}
		});
		searchWithPath(path);

		// listview item设定监听事件
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				// 点击item触发播放事件
				// 调用本地播放器
				Intent it = new Intent(Intent.ACTION_VIEW);
				// 播放路径以及指定播放类型格式为mp3
				it.setDataAndType(Uri.parse("file://" + root[arg2]),
						"audio/MP3");
				startActivity(it);
			}
		});
		// 长按删除所选item列表事件
//		listView.setOnItemLongClickListener(new OnItemLongClickListener() {
//
//			@Override
//			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
//					final int arg2, long arg3) {
//				// TODO Auto-generated method stub
//				if(root[arg2]==null){
//					Toast.makeText(RecordtimeActivity.this, "该音频已删除，请刷新列表", Toast.LENGTH_LONG).show();
//				}else{
//				SimpleAlterDialog simpleAlterDialog = new SimpleAlterDialog(
//						R.string.btn_delete, true, R.string.btn_queding,
//						RecordtimeActivity.this, new CallBackListener() {
//
//							@Override
//							public void callback(Activity baseactivity) {
//								// TODO Auto-generated method stub
//								File file = new File(root[arg2]);
//								file.delete();
//								root[arg2]=null;
// 
//							} 
//
//						});
//				simpleAlterDialog.showDialog();
//			}
//				return false;
//			}
//
//		});
	}

	private void searchWithPath(String path) {
		textView = (TextView) findViewById(R.id.text1);
		/**
		 * 加载指定文件夹的音频文件
		 */
		System.out.println("path====== path=====" + path);
		String[] projection = new String[] { MediaStore.Audio.Media._ID,
				MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA,
				MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ARTIST };
		Cursor cursor = this.getContentResolver().query(
				MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection,
				MediaStore.Audio.Media.DATA + " like '" + path + "%'", null,
				null);

		counter = cursor.getCount();
		/*
		 * 给每个数组定义长度
		 * 长度为音频文件个数
		 */
		data = new String[counter];// 保存每一个音频录取日期
		time = new String[counter];// 保存每个音频录取时间
		time_length = new String[counter];// 保存每个音频时间长度
		root = new String[counter];// 每個文件的路徑
		cursor.moveToFirst();
/**
 * 将指定文件夹里的每个音频文件的信息放入数组
 */
		for (int j = 0; j < counter; j++) {

			String nameString = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
			char a[] = nameString.toCharArray();
			year = a[0] + "" + a[1] + "" + a[2] + "" + a[3];
			mounth = a[4] + "" + a[5];
			day = a[6] + "" + a[7];
			Log.i("ss", year + "");
			hour = a[9] + "" + a[10];
			minuets = a[11] + "" + a[12];
			data[j] = year + "年" + mounth + "月" + day + "日";
			Log.i("ss", data[j] + "aaaaaaa");
			time[j] = hour + ":" + minuets;
			root[j] =  cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
			int times = Integer.parseInt(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION)));
			Time(times);
			if (second >= 60) {
				time_length[j] = minute + "分" + remain + "秒";
			} else {
                 time_length[j] = second + "秒";
			}		
			cursor.moveToNext();
            adapter = new RecordAdapter(RecordtimeActivity.this, data, time,
					time_length);
			// 将listview加载进adapter
			listView.setAdapter(adapter);
		}
	}
/**
 * 将秒数转换成分钟
 * @param time
 */
	public void Time(int time) {
		second = time / 1000;// 把毫秒转换成秒
		if (second >= 60) {
			minute = second / 60;// 把秒转换成分钟
			remain = second - minute * 60;// 算出不足一分钟的秒数
		}

	}

	/**
	 * 手动扫描SD卡上的音频文件
	 */
	private void scanSdCard() {
		IntentFilter intentfilter = new IntentFilter(
				Intent.ACTION_MEDIA_SCANNER_STARTED);
		intentfilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
		intentfilter.addDataScheme("file");
		ScanSdReceiver scanSdReceiver = new ScanSdReceiver();
		RecordtimeActivity.this.registerReceiver(scanSdReceiver, intentfilter);
		sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
				Uri.parse("file://"
						+ Environment.getExternalStorageDirectory()
								.getAbsolutePath())));

	}

}